﻿using Core.Framework.Model.Common;
using Core.Framework.Model.WebSockets;
using Core.Framework.Redis.Queue_Helper;
using Core.Framework.Util;
using Core.Framework.Util.Common;
using Core.IBusiness.ILoggerModule;
using Core.Service.TaskHandle;
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Core.Middleware.WebSockets.TimerJobs
{
    /// <summary>
    /// 任务处理
    /// </summary>
    public class ExecQueueTask : ITimerJob
    {


        // 获取日志服务
        ILog iLog = BuildServiceProvider.GetService<ILog>();

        public void Execute(IJobExecutionContext context)
        {

            int 
                threadLength = context.MergedJobDataMap.GetIntValue("threadLength");


            var values = RedisQueueHelper.SortedPop(RedisQueueHelperParameter.Queue);

            if (values?.Length > 0)
            {
                Parallel.ForEach(values, new ParallelOptions {MaxDegreeOfParallelism = threadLength}, item =>
                {
                    MessageQueue value = ((string) item).TryToEntity<MessageQueue>(out string errmsg);

                    this.ExecTask(value);

                    iLog.Queue<ExecQueueTask>(new
                        {
                            Client = CoreStartupHelper.GetConfigValue("Service:Title")
                    }.TryToJson(),
                        "timedLoop",
                        value.ClientInfo.Project.ProjectToken,
                        value.Message.Token);

                });
            }

        }


        /// <summary>
        /// 任务处理
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        bool ExecTask(MessageQueue message)
        {
            bool result = true;

            if (null != message)
            {

                TaskHandleFactory.DoDispatch(message,
                    a => a.Template.ToLower() == message.Template.ToLower(),
                    (template, error) =>
                    {
                        result = false;

                        iLog.Queue<ExecQueueTask>(new
                            {
                                Client = CoreStartupHelper.GetConfigValue("Service:Title"),
                                Message = error
                        }.TryToJson(), "execTaskError",
                            message.ClientInfo.Project.ProjectToken,
                            message.Message.Token);

                    });
            }

            return result;
        }
    }
}
